package util;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.exif.GpsDescriptor;
import com.drew.metadata.exif.GpsDirectory;
import dto.EXIFData;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.apache.log4j.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Helper class to handle the EXIF data of images.
 * 
 * @author steffen
 * @version 0.1
 */
public class EXIFHelper {

    private static Logger logger = Logger.getLogger(EXIFHelper.class);

    /**
     *
     * @param pathName
     * @return
     * @throws IOException
     * @throws ImageProcessingException
     */
    public static EXIFData getEXIFData(String pathName)
            throws IOException, ImageProcessingException {

        File imageFile = new File(pathName);

        if (!imageFile.exists()) {
            throw new IOException("The given file doesnt exist! "
                    + pathName);
            
        }

        Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
        EXIFData data = new EXIFData();

        if (metadata.containsDirectory(ExifSubIFDDirectory.class)) {
            ExifSubIFDDirectory subDir = metadata.getDirectory(
                    ExifSubIFDDirectory.class);

            Date date = subDir.getDate(
                    ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);

        } else {
            logger.debug("No ExifSubIFDDirectory in " + pathName);
        }

        if (metadata.containsDirectory(GpsDirectory.class)) {

            GpsDescriptor gps = new GpsDescriptor(
                    metadata.getDirectory(GpsDirectory.class));

            StringToGeo(gps.getGpsLatitudeDescription());
            StringToGeo(gps.getGpsLongitudeDescription());
        } else {
            logger.debug("No GPS data in " + pathName);
        }

        return data;
    }

    /**
     * Converts DMS notated coordinates to the degree representation.
     *
     * The DMS must be in the format <b> f° f' f"</b>
     *
     * @param cord
     * @throws IllegalArgumentException
     * @throws NumberFormatException
     *
     * @return The degree Value of the DMS coordinate representation.
     */
    private static float StringToGeo(String cord) {
        String[] values = cord.split("[°'\" ]+");

        if (values.length < 3) {
            throw new IllegalArgumentException("Not enougth parameters found");
        }

        float deg = Float.parseFloat(values[0]);
        float min = Float.parseFloat(values[1]);
        float sec = Float.parseFloat(values[2]);

        sec += (min * 60);
        deg += (sec / 3600);

        return deg;
    }
}
